import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { ClientEntity } from './entities';
import { InjectRepository } from '@nestjs/typeorm';
import { ListClientDto } from './dto';
import { UserDto } from '../user/user.decorator';

@Injectable()
export class ClientService {
  constructor(
    @InjectRepository(ClientEntity)
    private readonly clientEntityRep: Repository<ClientEntity>,
  ) {}

  async findAll(query: ListClientDto, user: UserDto) {
    const entity = this.clientEntityRep.createQueryBuilder('client');
    const pageSize = query.pageSize || 10;
    const pageNum = query.pageNum || 1;
    const enterpriseId = user.enterpriseId;
    entity.leftJoinAndSelect('client.user', 'user');

    if (enterpriseId) {
      entity.andWhere(`user.enterpriseId = :enterpriseId`, { enterpriseId });
    }

    if (query.nickName) {
      entity.andWhere(`user.nickName LIKE "%${query.nickName}%"`);
    }

    if (query.phonenumber) {
      entity.andWhere(`user.phoneNumber = :phonenumber`, { phonenumber: query.phonenumber });
    }

    entity.skip(pageSize * (pageNum - 1)).take(pageSize);

    let [list, total] = await entity.getManyAndCount();
    const totalPage = Math.ceil(total / pageSize);
    return {
      list: list.map((item) => ({ ...item, ...item.user })),
      total,
      totalPage,
      pageNum,
      pageSize,
    };
  }
}
